
package com.scalar.chiptrack.operations.process.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.forms.ProductSetupForm;
import com.scalar.chiptrack.users.User;

public final class ProductSetupAction extends ChipTrackAction{

   public ActionForward execute (ActionMapping mapping, 
                                  ActionForm form, 
                                  HttpServletRequest request, 
                                  HttpServletResponse response) throws Exception 
	{

		HttpSession ses = request.getSession(true);
        ProductSetupForm productSetupForm = (ProductSetupForm) form;
		
		User user = (User) ses.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
		
		String baseProductName = productSetupForm.getBaseProductName();
		String sameAs = productSetupForm.getSameAs();
		String comments = productSetupForm.getComments();
		
		if( baseProductName == null || baseProductName.length() < 1 )
		{
			saveToken( request );
			return ( mapping.findForward( "exists" ) );
		}
		
		if( !isTokenValid(request) )
		{
			return ( mapping.findForward( "success" ) );
		}

        ProductDao productDao  = new ProductDao();
        String productId = productDao.saveBaseProduct(baseProductName,comments);
        	
		if( !productId.equals( "exists" ) )
		{
			ses.setAttribute( "productId" , productId );
			ses.setAttribute( "baseProductName" , baseProductName );
			resetToken(request);
			saveToken(request);
			return ( mapping.findForward( "success" ) );
		}
		else
		{
			request.setAttribute( "message" , "Base Product Name already exists" );
			request.setAttribute( "productsetup" , productSetupForm );
			return ( mapping.findForward( "exists" ) );
		}
	}

}